<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="addRolesBtn">添加角色</el-button>
      <!-- 角色列表区 -->
      <el-table :data="rolesList" stripe border style="width: 100%">
        <!-- 展开列表 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="[
                'borderBottom',
                index === 0 ? 'borderTop' : '',
                'vcenter',
              ]"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  type="primary"
                  closable
                  @close="removeRightById(scope.row, item.id)"
                  >{{ item.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item.children"
                  :key="item2.id"
                  :class="[i2 !== 0 ? 'borderTop' : '']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引 -->
        <el-table-column type="index" label="#" width="100"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column prop="children" label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRolesBtn(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-delete"
              size="mini"
              @click="removeRolesById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-s-tools"
              size="mini"
              @click="showSetRightsDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加用户的对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <!-- 文本的主体区域 -->
        <el-form
          :model="roleFrom"
          :rules="addFormRules"
          ref="roleFromRef"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="roleFrom.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="roleFrom.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改角色的对话框 -->
      <el-dialog
        title="修改角色信息"
        :visible.sync="editDialogVisible"
        width="50%"
      >
        <!-- 文本的主体区域 -->
        <el-form
          :model="editFrom"
          :rules="addFormRules"
          ref="editFormRef"
          label-width="100px"
        >
          <el-form-item label="角色名" prop="roleName">
            <el-input v-model="editFrom.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editFrom.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="emitRolesById">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限角色对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="rightsdialogVisible"
        width="50%"
        @close="setRightDialogClosed"
      >
        <el-tree
          :data="rightsList"
          :props="treeProps"
          default-expand-all
          node-key="id"
          show-checkbox
          :default-checked-keys="defKeys"
          ref="treeRef"
        >
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rightsdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      rolesList: [],
      // 控制添加角色弹出层
      addDialogVisible: false,
      // 控制修改弹出层
      editDialogVisible: false,
      // 控制权限分配弹出层
      rightsdialogVisible: false,
      // 添加角色数据
      roleFrom: {
        roleName: '',
        roleDesc: '',
      },
      // 修改角色数据
      editFrom: {
        roleName: '',
        roleDesc: '',
      },
      // 树形控件的属性的绑定
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      // 权限来表数据
      rightsList: {},
      // 默认选中的数组权限
      defKeys: [],
      roleId: '',
      // 添加角色的验证规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        roleDesc: [{ required: true, message: '请输入描述', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 添加角色按钮
    addRolesBtn() {
      this.addDialogVisible = true
    },
    // 添加用户的确定按钮
    addRoles() {
      this.$refs.roleFromRef.validate(async (valid) => {
        if (!valid) return false
        const { data: res } = await this.$http.post('roles', this.roleFrom)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色失败成功！')
        this.addDialogVisible = false
        this.getRolesList()
      })
    },
    // 重置添加角色弹出框表单
    addDialogClose() {
      this.$refs.roleFromRef.resetFields()
    },
    // 删除角色
    async removeRolesById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 确认返回 confirm
      // 取消返回 cancel
      console.log(confirmResult)
      if (confirmResult === 'cancel') {
        return this.$message.info('取消删除角色！')
      }
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功！')
      this.getRolesList()
    },
    // 编辑按钮
    editRolesBtn(role) {
      this.editDialogVisible = true
      this.editFrom = role
    },
    // 修改角色的id
    emitRolesById() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return false
        const { data: res } = await this.$http.put(
          `roles/${this.editFrom.id}`,
          { roleName: this.editFrom.roleName, roleDesc: this.editFrom.roleDesc }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色失败！')
        }
        this.$message.success('修改角色失败成功！')
        this.editDialogVisible = false
        this.getRolesList()
      })
    },
    // 获取角色权限列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色权限列表失败！')
      }
      this.rolesList = res.data
    },
    // 删除角色权限
    async removeRightById(role, rightId) {
      console.log(role)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 确认返回 confirm
      // 取消返回 cancel

      if (confirmResult === 'cancel') {
        return this.$message.info('取消删除！')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户权限失败！')
      }
      // 传递过来的形参本事就是一个响应数据,可以直接对权限三的数据进行修改
      role.children = res.data
    },
    // 分配权限按钮
    async showSetRightsDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败!')
      }
      this.rightsList = res.data
      // 递归获取三级权限
      this.getLeafKeys(role, this.defKeys)
      this.rightsdialogVisible = true
    },
    // 通过递归的形式,获取角色下所有的三级权限id,并保存 defkeys 数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    // 关闭分配权限对话框
    setRightDialogClosed() {
      this.defKeys = []
    },
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getHalfCheckedKeys(),
        ...this.$refs.treeRef.getCheckedKeys(),
      ]
      const idstr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idstr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败!')
      }
      this.$message.success('分配权限成功!')
      this.rightsdialogVisible = false
      this.getRolesList()
    },
  },
}
</script>

<style lang="less" scoped>
.borderTop {
  border-top: 1px solid #eee;
}
.borderBottom {
  border-bottom: 1px solid #eee;
}

.el-tag {
  margin: 7px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
